import React, { useState } from 'react';
import {
  View,
  Text,
  FlatList,
  StyleSheet,
  TouchableOpacity,
  Modal,
  TextInput,
  Alert,
} from 'react-native';
import { colors, shadows, spacing } from '../../styles';
import Icon from '../../components/Icon';
import { useDeck } from './DeckContext';
import { Deck, Card } from './types';

interface DeckDetailProps {
  deck: Deck;
  onStartReview: (deck: Deck) => void;
  onBack: () => void;
}

const DeckDetail: React.FC<DeckDetailProps> = ({
  deck,
  onStartReview,
  onBack,
}) => {
  const { addCard, deleteCard, getDueCards } = useDeck();
  const [modalVisible, setModalVisible] = useState(false);
  const [cardFront, setCardFront] = useState('');
  const [cardBack, setCardBack] = useState('');
  const [editingCard, setEditingCard] = useState<Card | null>(null);

  const dueCards = getDueCards(deck.id);

  const handleAddCard = () => {
    if (cardFront.trim() && cardBack.trim()) {
      addCard(deck.id, cardFront.trim(), cardBack.trim());
      setCardFront('');
      setCardBack('');
      setModalVisible(false);
    } else {
      Alert.alert('提示', '请输入卡片正反面内容');
    }
  };

  const handleUpdateCard = () => {
    if (editingCard && cardFront.trim() && cardBack.trim()) {
      // 删除旧卡片
      deleteCard(deck.id, editingCard.id);
      // 添加新卡片（使用相同的ID）
      addCard(deck.id, cardFront.trim(), cardBack.trim());
      setCardFront('');
      setCardBack('');
      setEditingCard(null);
      setModalVisible(false);
    } else {
      Alert.alert('提示', '请输入卡片正反面内容');
    }
  };

  const handleDeleteCard = (cardId: string) => {
    Alert.alert('确认删除', '确定要删除这张卡片吗？', [
      { text: '取消', style: 'cancel' },
      {
        text: '删除',
        style: 'destructive',
        onPress: () => deleteCard(deck.id, cardId),
      },
    ]);
  };

  const handleEditCard = (card: Card) => {
    setEditingCard(card);
    setCardFront(card.front);
    setCardBack(card.back);
    setModalVisible(true);
  };

  const renderCardItem = ({ item }: { item: Card }) => {
    const isDue = !item.nextReviewDate || item.nextReviewDate <= new Date();

    return (
      <TouchableOpacity
        style={styles.cardItem}
        onLongPress={() => handleDeleteCard(item.id)}
      >
        <View style={styles.cardContent}>
          <View style={styles.cardSide}>
            <Text style={styles.sideLabel}>正面:</Text>
            <Text style={styles.sideText} numberOfLines={2}>
              {item.front}
            </Text>
          </View>
          <View style={styles.cardDivider} />
          <View style={styles.cardSide}>
            <Text style={styles.sideLabel}>反面:</Text>
            <Text style={styles.sideText} numberOfLines={2}>
              {item.back}
            </Text>
          </View>
        </View>
        <View style={styles.cardActions}>
          <TouchableOpacity
            style={styles.editButton}
            onPress={() => handleEditCard(item)}
          >
            <Text style={styles.editButtonText}>编辑</Text>
          </TouchableOpacity>
        </View>
        <View style={styles.cardStats}>
          <Text style={styles.statsLabel}>
            复习次数: {item.repetitions} | 间隔: {item.interval}天
            {isDue && <Text style={styles.dueTag}> • 待复习</Text>}
          </Text>
        </View>
      </TouchableOpacity>
    );
  };

  return (
    <View style={styles.container}>
      {/* Header */}
      <View style={styles.header}>
        <View style={styles.headerInfo}>
          <Text style={styles.deckName}>{deck.name}</Text>
          {deck.description && (
            <Text style={styles.deckDescription}>{deck.description}</Text>
          )}
        </View>
      </View>

      {/* Stats */}
      <View style={styles.statsContainer}>
        <View style={styles.statBox}>
          <Text style={styles.statNumber}>{deck.cards.length}</Text>
          <Text style={styles.statLabel}>总卡片</Text>
        </View>
        <View style={styles.statBox}>
          <Text style={[styles.statNumber, styles.dueNumber]}>
            {dueCards.length}
          </Text>
          <Text style={styles.statLabel}>待复习</Text>
        </View>
      </View>

      {/* Start Review Button */}
      {dueCards.length > 0 && (
        <TouchableOpacity
          style={styles.reviewButton}
          onPress={() => onStartReview(deck)}
        >
          <Text style={styles.reviewButtonText}>开始复习</Text>
        </TouchableOpacity>
      )}

      {/* Cards List */}
      <FlatList
        data={deck.cards}
        renderItem={renderCardItem}
        keyExtractor={item => item.id}
        contentContainerStyle={styles.listContent}
        ListEmptyComponent={
          <View style={styles.emptyContainer}>
            <Text style={styles.emptyText}>还没有卡片</Text>
            <Text style={styles.emptyHint}>点击右下角 + 按钮添加</Text>
          </View>
        }
      />

      {/* FAB */}
      <TouchableOpacity
        style={styles.fab}
        onPress={() => {
          setEditingCard(null);
          setCardFront('');
          setCardBack('');
          setModalVisible(true);
        }}
      >
        <Text style={styles.fabText}>+</Text>
      </TouchableOpacity>

      {/* Add/Edit Card Modal */}
      <Modal
        visible={modalVisible}
        transparent
        animationType="fade"
        onRequestClose={() => setModalVisible(false)}
      >
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <Text style={styles.modalTitle}>
              {editingCard ? '编辑卡片' : '新建卡片'}
            </Text>

            <Text style={styles.inputLabel}>正面</Text>
            <TextInput
              style={[styles.input, styles.textArea]}
              placeholder="输入问题或单词..."
              placeholderTextColor={colors.text.secondary}
              value={cardFront}
              onChangeText={setCardFront}
              multiline
              numberOfLines={3}
            />

            <Text style={styles.inputLabel}>反面</Text>
            <TextInput
              style={[styles.input, styles.textArea]}
              placeholder="输入答案或解释..."
              placeholderTextColor={colors.text.secondary}
              value={cardBack}
              onChangeText={setCardBack}
              multiline
              numberOfLines={3}
            />

            <View style={styles.modalButtons}>
              <TouchableOpacity
                style={[styles.button, styles.cancelButton]}
                onPress={() => {
                  setModalVisible(false);
                  setCardFront('');
                  setCardBack('');
                  setEditingCard(null);
                }}
              >
                <Text style={styles.cancelButtonText}>取消</Text>
              </TouchableOpacity>

              <TouchableOpacity
                style={[styles.button, styles.confirmButton]}
                onPress={editingCard ? handleUpdateCard : handleAddCard}
              >
                <Text style={styles.confirmButtonText}>
                  {editingCard ? '更新' : '创建'}
                </Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: spacing.padding.lg,
  },
  headerInfo: {
    flex: 1,
    alignItems: 'center',
  },
  deckName: {
    fontSize: 20,
    fontWeight: '600',
    color: colors.text.primary,
  },
  deckDescription: {
    fontSize: 14,
    color: colors.text.secondary,
    marginTop: 4,
  },
  statsContainer: {
    flexDirection: 'row',
    padding: spacing.padding.lg,
    justifyContent: 'space-around',
  },
  statBox: {
    alignItems: 'center',
  },
  statNumber: {
    fontSize: 32,
    fontWeight: '600',
    color: colors.primary,
  },
  dueNumber: {
    color: colors.danger,
  },
  statLabel: {
    fontSize: 14,
    color: colors.text.secondary,
    marginTop: 4,
  },
  reviewButton: {
    backgroundColor: colors.primary,
    marginHorizontal: spacing.margin.lg,
    marginBottom: spacing.margin.md,
    padding: spacing.padding.md,
    borderRadius: 12,
    alignItems: 'center',
    ...shadows.md,
  },
  reviewButtonText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: '600',
  },
  listContent: {
    padding: spacing.padding.md,
  },
  cardItem: {
    backgroundColor: colors.surface,
    padding: spacing.padding.md,
    marginBottom: spacing.margin.md,
    borderRadius: 12,
    ...shadows.sm,
  },
  cardContent: {
    marginBottom: 8,
  },
  cardSide: {
    marginVertical: 4,
  },
  cardDivider: {
    height: 1,
    backgroundColor: colors.border.light,
    marginVertical: 8,
  },
  sideLabel: {
    fontSize: 12,
    color: colors.text.tertiary,
    marginBottom: 4,
  },
  sideText: {
    fontSize: 16,
    color: colors.text.primary,
  },
  cardActions: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    marginVertical: 8,
  },
  editButton: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    backgroundColor: colors.primary,
    borderRadius: 4,
  },
  editButtonText: {
    color: '#fff',
    fontSize: 14,
    fontWeight: '500',
  },
  cardStats: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  statsLabel: {
    fontSize: 12,
    color: colors.text.secondary,
  },
  dueTag: {
    color: colors.danger,
    fontWeight: '600',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 100,
  },
  emptyText: {
    fontSize: 18,
    color: colors.text.secondary,
    marginBottom: 8,
  },
  emptyHint: {
    fontSize: 14,
    color: colors.text.secondary,
  },
  fab: {
    position: 'absolute',
    right: 20,
    bottom: 20,
    width: 56,
    height: 56,
    borderRadius: 28,
    backgroundColor: colors.primary,
    justifyContent: 'center',
    alignItems: 'center',
    ...shadows.lg,
  },
  fabText: {
    fontSize: 32,
    color: '#fff',
    fontWeight: '300',
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalContent: {
    width: '85%',
    backgroundColor: colors.surface,
    borderRadius: 16,
    padding: 24,
    ...shadows.lg,
  },
  modalTitle: {
    fontSize: 20,
    fontWeight: '600',
    color: colors.text.primary,
    marginBottom: 20,
    textAlign: 'center',
  },
  inputLabel: {
    fontSize: 14,
    fontWeight: '500',
    color: colors.text.primary,
    marginBottom: 8,
  },
  input: {
    backgroundColor: colors.background,
    borderRadius: 8,
    padding: 12,
    fontSize: 16,
    color: colors.text.primary,
    marginBottom: 16,
    borderWidth: 1,
    borderColor: colors.border.primary,
  },
  textArea: {
    height: 80,
    textAlignVertical: 'top',
  },
  modalButtons: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 12,
  },
  button: {
    flex: 1,
    padding: 12,
    borderRadius: 8,
    alignItems: 'center',
  },
  cancelButton: {
    backgroundColor: colors.background,
    marginRight: 8,
  },
  confirmButton: {
    backgroundColor: colors.primary,
    marginLeft: 8,
  },
  cancelButtonText: {
    color: colors.text.primary,
    fontSize: 16,
    fontWeight: '500',
  },
  confirmButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '500',
  },
});

export default DeckDetail;
